#!/bin/bash
# Portable start script that does not require Gradle on the target machine.
# Usage:
#   APP_JAR=/path/to/app.jar JVM_OPTS='-Xmx1g' ./start.sh

set -euo pipefail

echo "Starting score-tj..."

# If APP_JAR env var is set, use it. Otherwise try to find a jar in common locations.
if [[ -n "${APP_JAR:-}" ]]; then
	JAR_PATH="$APP_JAR"
else
	# search order: ./dist/*.jar, ./build/libs/*.jar, ./lib/*.jar, ./*.jar
	if compgen -G "dist/*.jar" > /dev/null; then
		JAR_PATH=$(ls -t dist/*.jar | head -n 1)
	elif compgen -G "build/libs/*.jar" > /dev/null; then
		JAR_PATH=$(ls -t build/libs/*.jar | head -n 1)
	elif compgen -G "lib/*.jar" > /dev/null; then
		JAR_PATH=$(ls -t lib/*.jar | head -n 1)
	elif compgen -G "*.jar" > /dev/null; then
		JAR_PATH=$(ls -t *.jar | head -n 1)
	else
		echo "ERROR: No application jar found. Please provide APP_JAR or place the jar in ./dist, ./build/libs, ./lib or current directory." >&2
		exit 2
	fi
fi

echo "Using JAR: $JAR_PATH"

# Default JVM options (can be overridden with JVM_OPTS env var)
: ${JVM_OPTS:="-Xms256m -Xmx1g -Dfile.encoding=UTF-8"}

echo "JVM options: $JVM_OPTS"

# Ensure database directory exists when using file-mode H2
DB_DIR="./database"
if [[ -d "$DB_DIR" ]]; then
	echo "Database directory exists: $DB_DIR"
else
	echo "Database directory not found, creating: $DB_DIR"
	mkdir -p "$DB_DIR"
fi

echo "Starting Java process..."
exec java $JVM_OPTS -jar "$JAR_PATH"